<?php

namespace app\api\controller;

use app\api\controller\Tpmecms;
use think\Db;
use think\Config;
use think\Cache;
/**
 * 动态空间
 */
class Zone extends Tpmecms
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    // public function test()
    // {
    //     $this->success('返回成功', $this->request->param());
    // }

    /**
     * 获取我动态列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_my_list($page=1,$limit=5)
    {
        $list = Db::name('zone')->where('uid',$this->auth->id)->order('time desc')->page($page,$limit)->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldZoneListData($val);
            }
        }

        $this->success('ok', $list);
    }

    /**
     * 发布动态
     *
     * @param string $content 发布内容
     * @param string $images 图集
     * @param string $image 封面图
     * @param string $image_status 图片:1=用户自传,2=平台图
     * @param string $type_status 类型:1=普通用户,2=广告
     * @return void
     */
    public function add_zone($content=null,$images=null,$image=null,$image_status,$type_status='1')
    {

        $this->IsAddZone();//是否可以发布
        if($content || $images || $image_status){
            $this->VerifyStr($content);//验证违禁词
            $data['content'] = $content;
            $data['images'] = $images;

            $data['image'] = $image;
            $data['image_status'] = $image_status;

            $data['time'] = time();
            $data['uid'] = $this->auth->id;
            $data['school_id'] = $this->auth->school_id;

            $data['type_status'] = '1';//类型:1=普通用户,2=广告
            switch ($type_status) {
                case '1':
                    
                    break;
                case '2':
                    if($this->auth->adv_switch==1){//adv_switch //sys_status
                        $data['type_status'] = '2';//'类型:1=普通用户,2=广告';
                    }else{
                        $this->error('没广告权限');
                    }
                    break;
                default:
                    # code...
                    break;
            }
           

            $id = Db::name('zone')->insertGetId($data);
            $this->success('发布成功',$id);
        }else{
            $this->error('请上传一些内容');
        }
    }

    /**
     * 删除我的某个动态
     *
     * @param int $id 动态id
     * @return void
     */
    public function del_zone($id)
    {
        $zone = Db::name('zone')->where('id',$id)->find();
        if(!$zone){
                $this->error('该动态不存在');
        }
        if($zone['uid']!=$this->auth->id){
            $this->error('你没有该动态');
        }
        Db::name('zone')->where('id',$id)->delete();
        $this->DelZoneCommentByzone_id($id);
        $this->success('删除成功');
    }



    /**
     * 删除我的评论
     *
     * @param int $id 评论id
     * @return void
     */
    public function del_me_comment($id)
    {
        $comment = Db::name('zone_comment')->where('id',$id)->where('uid',$this->auth->id)->find();
        if(!$comment){
            $this->error('该评论不存在');
        }
        $ids = [$id];
        //删除下级评论
        $xia_ids = Db::name('zone_comment')->where('top_id',$id)->column('id');
        if($xia_ids){
            $ids = array_merge($xia_ids,$ids);
            //在找下级
            $xia2_ids = Db::name('zone_comment')->where('top_id','in',$xia_ids)->column('id');
            if($xia2_ids){
                $ids = array_merge($xia2_ids,$ids);
            }
        }
        
        $res = Db::name('zone_comment')->where('id','in',$ids)->delete();
        $this->success('删除成功',$res);
    }



    /**
     * 获取用户的信息
     *
     * @param int $uid 用户id
     * @return void
     */
    public function get_user_data($uid)
    {
        $user['user'] = Db::name('user')->where('id',$uid)->find();
        if(!$user['user']){
            $this->error('该用户不存在');
        }
        $user['follow'] = Db::name('fans')->where('fans_uid',$uid)->count();
        $user['fans'] = Db::name('fans')->where('uid',$this->auth->id)->count();
        $user['character'] = Db::name('character')->where('id','in',$user['user']['character_ids'])->column('name');//个性
        $user['school'] = Db::name('school')->where('id',$user['user']['school_id'])->value('name');//学校名
        $user['isfollow'] = $this->GetMyIsfollowUser($uid);
        $user['ta_follow'] = $this->GetUserIsfollowMy($uid);


        $this->success('ok',$user);
    }



    /**
     * 获取所有的动态空间列表
     *
     * @param integer $school_id 学校ID(可不传)
     * @param integer $page 1
     * @param integer $limit 10
     * @param integer $again 再次打开
     * @return void
     */
    public function get_zone_list($school_id=null,$page=1,$limit=10,$again=null)
    {

        //清除浏览记录
        if($again){
            Cache::set('zone_look_uid'.$this->auth->id,0);
        }
        // $where = null;
        // if($school_id)
        // $where['school_id'] = $school_id;

        // $list = Db::name('zone')->where($where)->order('time desc')->page($page,$limit)->select();
        // if($list){
        //     foreach ($list as $key => &$val) {
        //         $val = $this->ChangeFieldZoneListData($val);
        //     }
        // }

        for ($i=0; $i <= $limit; $i++) { 
            $list[] = $this->get_rand_zone($school_id,null,true);
        }
        
        $this->success('ok', $list);
    }





    /**
     * 获取随机1个人的动态空间
     *
     * @param integer $school_id 学校ID(可不传)
     * @param integer $type_status 类型:1=普通用户,2=广告（默认1
     * @return void
     */
    public function get_rand_zone($school_id=null,$type_status=null,$self=false)
    {
        $where = null;
        if(!$type_status)
            $type_status = '1';




        if($type_status=='1'){//如果是获取普通的
            $where['type_status'] = '1';
            if($school_id)
                $where['school_id'] = $school_id;


            if($this->IsGetJoinAdv()){  //判断是否该插入广告
                // $type_status = '2'; 
                $where['type_status'] = '2';
                if(Db::name('zone')->where($where)->count()>0){
                    $where['type_status'] = '2';
                }else{
                    // unset($where['type_status']);
                    $where['type_status'] = '1';
                }
            }
        }else{
            $where['type_status'] = $type_status;
        }


        
        

        $val = Db::name('zone')
                ->where($where)

                // ->where('rand()')
                // ->orderRand()
                // ->order('time desc')
                
                ->orderRaw('rand()')
                ->limit(1)
                // ->fetchSql(true)
                ->find();
        // halt($val);
        if($val){
            $this->IncZoneLook($val['id'],$val['type_status']);
            $val = $this->ChangeFieldZoneListData($val);
        }
        
        if($self){
            return $val;
        }else{
            $this->success('ok', $val);
        }

    }

    /**
     * 是否插入广告
     *
     * @return void
     */
    protected function IsGetJoinAdv()
    {
        $num = Cache::get('zone_look_uid'.$this->auth->id);

        $f = Config::get('site.first_how_many_zone_one_adv');
        $n = Config::get('site.how_many_zone_one_adv');
        // $num = Db::name('zone_look')->where('uid',$this->auth->id)->order('time desc')->value('num');
        //first_how_many_zone_one_adv
        if($num){
            if($num>$n){
                if(($num-$f)%($n+1)==0)
                    return true;
            }else{
                if($num==$f)
                    return true;
            }
         
        }
        return false;
    }

    /**
     * 插入记录
     *
     * @param int $zone_id 动态id
     * @param string $type_status 类型:1=普通用户,2=广告
     * @return void
     */
    protected function IncZoneLook($zone_id,$type_status='1')
    {

     
        $num = Cache::get('zone_look_uid'.$this->auth->id);
        $num++;
        Cache::set('zone_look_uid'.$this->auth->id,$num);
        // if(!$num || $num==null){
        //     Cache::set('zone_look_uid'.$this->auth->id,0);
        // }else{
            
        //     Cache::set('zone_look_uid'.$this->auth->id,$num+1);
        //     // if($num>=Config::get('site.how_many_zone_one_adv')){
        //     //     $num = 0;
        //     //     Cache::set('zone_look_uid'.$this->auth->id,0);
        //     // }else{
        //     //     $num = $num + 1;
        //     //     Cache::set('zone_look_uid'.$this->auth->id,$num);
        //     // }
        // }


        Db::name('zone_look')->insert(['zone_id'=>$zone_id,'uid'=>$this->auth->id,'time'=>time(),'num'=>$num]);
        $this->IncZoneViews($zone_id);
    }

    /**
     * 获取用户的动态空间列表
     *
     * @param integer $uid 用户ID
     * @param integer $page 1
     * @param integer $limit 10
     * @return void
     */
    public function get_user_zone_list($uid,$page=1,$limit=10)
    {
        $list = Db::name('zone')->where('uid',$uid)->order('time desc')->page($page,$limit)->select();
        if($list){
            foreach ($list as $key => &$val) {
                $val = $this->ChangeFieldZoneListData($val);
            }
        }
        $this->success('ok', $list);
    }

    /**
     * 获取动态详情
     *
     * @param int $id 动态ID
     * @return void
     */
    public function get_data($id)
    {
        $val = Db::name('zone')->where('id',$id)->find();
        if($val){
            $val = $this->ChangeFieldZoneData($val);
        }else{
            $this->error('该动态不存在');
        }
        $this->IncZoneViews($id);
        $this->success('ok', $val);

    }


    /**
     * 改变空间字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldZoneListData($val){
        // $val['comment'] = $this->GetZoneCommentArray($val['id']);//获取空间评论列表
        $val['user'] = $this->GetUserData2($val['uid']);
        $val['m'] = date('n',$val['time']);
        $val['d'] = date('d',$val['time']);
        $val['date_str'] = $this->TimeToStr($val['time']);
        $val['comment_num'] = $this->GetZoneCommentNum($val['id']);
        $val['self_likes'] = $this->GetUserIsZonelikes($val['id'],$this->auth->id);
        return $val;
    }



     /**
     * 改变空间字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldZoneData($val){
        $val['comment'] = $this->GetZoneCommentArray($val['id']);//获取空间评论列表
        $val['user'] = $this->GetUserData2($val['uid']);
        $val['m'] = date('n',$val['time']);
        $val['d'] = date('d',$val['time']);
        $val['comment_num'] = $this->GetZoneCommentNum($val['id']);
        $val['self_likes'] = $this->GetUserIsZonelikes($val['id'],$this->auth->id);
        $val['date_str'] = $this->TimeToStr($val['time']);
        $val['isfollow'] = $this->GetMyIsfollowUser($val['uid']);
        return $val;
    }

    /**
     * 评论动态
     *
     * @param int $zone_id 动态id
     * @param string $content 内容
     * @param string $images 图集(可不传)
     * @param int $comment_id 评论id(可不传)
     * @return void
     */
    public function add_comment($zone_id,$content=null,$comment_id=null,$images=null)
    {
        $val = Db::name('zone')->where('id',$zone_id)->find();
        if(!$val){
            $this->error('该动态不存在');
        }
        $where['zone_id'] = $zone_id;
        $this->VerifyStr($content);
        if($comment_id){

            $res = Db::name('zone_comment')->where('id',$comment_id)->where($where)->find();
            if(!$res){
                $this->error('该评论不存在');
            }
            if($res['comment_id']>0){
                $where['top_id'] = $res['top_id'];
            }else{
                $where['top_id'] = $comment_id;
            }
            $where['comment_uid'] = $res['uid'];//被评论的用户id
            // $where['top_status'] = '2';
        }else{
            // $where['top_status'] = '1';
        }
        $where['comment_id'] = $comment_id;
        
        $where['content'] = $content;
        $where['images'] = $images;
        $where['uid'] = $this->auth->id;
        $where['time'] = time();     

        $id = Db::name('zone_comment')->insertGetId($where);

        // $this->AddMsg($uid,$status,$public_id,$user_id=null,$title=null);//类型:1=动态点赞,2=动态评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息
        if($comment_id){
            if($res['uid']!=$this->auth->id)//自己评论自己不添加
            $this->AddMsg($res['uid'],2,$zone_id,$this->auth->id,$this->auth->nickname.'给你动态评论了');
        }else{
            if($val['uid']!=$this->auth->id)//自己评论自己不添加
            $this->AddMsg($val['uid'],2,$zone_id,$this->auth->id,$this->auth->nickname.'给你动态评论了');
        }
     


        $this->success('评论成功', $id);
    }


    
    /**
     * 修改点赞
     *
     * @param int $zone_id 动态id
     * @return void
     */
    public function update_likes($zone_id)
    {
        $data['uid'] = $this->auth->id;
        $data['zone_id'] = $zone_id;
        $zone = Db::name('zone')->where('id',$zone_id)->find();
        $res = Db::name('zonelikes')->where($data)->find();
        if(!$res){
            $data['time'] = time();
            if(!$zone)$this->error('该动态不存在');
            $data['zone_uid'] = $zone['uid'];
            $data['id'] = Db::name('zonelikes')->insertGetId($data);
            //点赞数+1
            $this->IncZoneLikes($zone_id);

            // $this->AddMsg($uid,$status,$public_id,$user_id=null,$title=null);//类型:1=动态点赞,2=动态评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息
            $this->AddMsg($zone['uid'],1,$zone_id,$this->auth->id,$this->auth->nickname.'给你动态点赞了');

            $this->success('点赞成功',1);
        }else{
            Db::name('zonelikes')->where('id',$res['id'])->delete();
            //点赞数-1
            $this->DecZoneLikes($zone_id);

            // $this->AddMsg($zone['uid'],1,$zone_id,$this->auth->id,$this->auth->nickname.'给你动态取消点赞了');


            $this->success('取消点赞',0);
        }
    }



}
